﻿if select(2, UnitClass('player')) ~= "SHAMAN" then
	return
end
local deformat = AceLibrary("Deformat-2.0");
local L = AceLibrary("AceLocale-2.2"):new("Yata");
local BS = AceLibrary("Babble-Spell-2.2");
local SML = AceLibrary("SharedMedia-1.0");

----------
-- Init --
----------

function Yata:InitTimerOptions()
	local options = Yata.options.args.totemtimers.args;
	options["timerenable"] = {
		name = L["Enable Totem Timers"],
		desc = L["Enable Totem Timers"],
		type = "toggle",
		get = function() return self.db.profile.TimersEnabled end,
		set = function(v)
			self.db.profile.TimersEnabled = v;
			if(self.IsInitialized) then
				self:SaveTimersPosition();
			end
		end,		
	};
	options["timerbarscale"] = {
		name = L["Scale Totem Timer bars"],
		desc = L["Scale Totem Timer bars"],
		type = "range",
		get = function() return self.db.profile.TimerBarScale end,
		set = function(v)
			self.db.profile.TimerBarScale = v;
			if(self.IsInitialized) then
				self.CandyAnchorFrame:SetScale(self.db.profile.TimerBarScale);
				self:SaveTimersPosition();
			end
		end,
		min = 0.5,
		max = 1.5,
		step = 0.01,
		bigStep = 0.05,
		disabled = function() return InCombatLockdown() end,
	};
	options["timerbartexture"] = {
		type = "text",
		name = L["Timerbar Texture"],
		desc = L["Sets the timerbar texture"],
		get = function() return self.db.profile.TimerBarTexture end,
		set = function(v)
			if(self.IsInitialized) then
				self.db.profile.TimerBarTexture = v;
				self.TimerBarTextureHandle = SML:Fetch("statusbar",v);
			end
		end,
		validate = SML:List("statusbar"),
		disabled = function() return InCombatLockdown() end,
	};
	options["timerlock"] = {
		name = L["Lock Totem Timer bars"],
		desc = L["Lock Totem Timer bars"],
		type = "toggle",
		get = function() return self.db.profile.TimerBarLocked end,
		set = function(v)
			self.db.profile.TimerBarLocked = v;
			if(self.IsInitialized) then
				if(v) then
				 	self.CandyAnchorFrame:Hide();
				else
					self.CandyAnchorFrame:Show();
				end
				self:SaveTimersPosition();
			end;
		end,
		disabled = function() return InCombatLockdown() end,
	};
	
	self.formatStrings = {
		SPELLLOGCRITOTHEROTHER,
		SPELLLOGCRITSCHOOLOTHEROTHER,
		SPELLLOGOTHEROTHER,
		SPELLLOGSCHOOLOTHEROTHER,
		COMBATHITCRITOTHEROTHER,
		COMBATHITOTHEROTHER,
	};
end

function Yata:InitTimers()
	self:RegisterEvent("PLAYER_DEAD");
	-- Watch for damage done to our totems
	self:RegisterEvent("CHAT_MSG_SPELL_CREATURE_VS_SELF_DAMAGE", "TotemDamage");
	self:RegisterEvent("CHAT_MSG_COMBAT_CREATURE_VS_SELF_HITS", "TotemDamage");
	self:RegisterEvent("CHAT_MSG_SPELL_HOSTILEPLAYER_DAMAGE", "TotemDamage");
	self:RegisterEvent("CHAT_MSG_COMBAT_HOSTILEPLAYER_HITS", "TotemDamage");
	self:RegisterEvent("UNIT_SPELLCAST_SUCCEEDED");
	self:RegisterEvent("ZONE_CHANGED_NEW_AREA");
	self:RegisterEvent("SharedMedia_Registered","UpdateSharedMedia");
	self:RegisterEvent("SharedMedia_SetGlobal","UpdateSharedMedia");
	self:RegisterCandyBarGroup("YataCandy");
	self:SetCandyBarGroupGrowth("YataCandy",false);
end
function Yata:ZONE_CHANGED_NEW_AREA()
	if(not self.IsInitialized) then return end;
	-- remove our totem timers
	for k,b in pairs(self.TotemBar.Buttons) do
		if(b.TimeStart) then
			self:StopTimer(b.ButtonID);
		end
	end
	-- now let's see if we're in an arena to reset cooldown timers too, since it won't return proper values scheduleevent it after 10s
	self:ScheduleEvent("YataRemoveArenaCooldowns", function()
		local isArena, isRegistered = IsActiveBattlefieldArena();
		if(isArena) then
			for k,b in Yata.TotemBar:TotemButtons() do
				if(b.Totem.Cooldown > 0) then
					Yata:StopCandyBar(b.Totem.Name.."CooldownBar");
				end
			end	
	
		end
	end, 10);
end
function Yata:PLAYER_DEAD()
	if(self.db.profile.TimersEnabled) then
		for k,b in pairs(self.TotemBar.Buttons) do
			if(b.TimeStart) then
				self:StopTimer(b.ButtonID);
			end
		end
	end
end
function Yata:UpdateSharedMedia()
	self.TimerBarTextureHandle = SML:Fetch("statusbar",self.db.profile.TimerBarTexture);
end
-- TotemDamage function from GotWood by MoonSorrow
function Yata:TotemDamage(msg)
	if not string.find(string.lower(msg), string.lower(L["Totem"])) then return end
	local totem, dmg
	for _,v in ipairs(self.formatStrings) do
		local arg1, arg2, arg3, arg4 = deformat(msg, v)
		if arg4 and type(arg4)=='number' then
			totem, dmg = arg3, arg4
			break
		elseif arg2 and type(arg3)=='number' then
			totem, dmg = arg2, arg3
			break
		end
	end
	if not totem and not dmg then
    	local arg1, arg2, arg3, arg4 = deformat(msg, SPELLIMMUNEOTHER)
    	if arg2 == BS["Grounding Totem"] then
    	    totem = arg2
    	    dmg = 6 -- grounding totem has 5 life
    	end
	end
	if totem and dmg then
		for k,b in pairs(self.TotemBar.Buttons) do
			if(string.find(totem,b.Totem.Name) and b.CurrentHealth) then
				b.CurrentHealth = b.CurrentHealth - dmg;
				if(b.CurrentHealth <= 0 and b.TimeStart) then
					self:StopTimer(b.ButtonID);
				end
			break;
			end
		end
	end
end

function Yata:UNIT_SPELLCAST_SUCCEEDED(player, SpellName, sRank)
	if (player == "player") then 
		self:CheckHook(SpellName);
	end
end

function Yata:CandyAnchor()
	self.CandyAnchorFrame = {};
	self.CandyAnchorFrame = CreateFrame("Frame", "YATACANDYANCHOR", UIParent);
	self.CandyAnchorFrame:Hide();
	self.CandyAnchorFrame:SetWidth(250);
	self.CandyAnchorFrame:SetHeight(100);
	self.CandyAnchorFrame:SetBackdrop({bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background", tile = true, tileSize = 16,
					edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
					edgeSize = 16, insets = {left = 4, right = 4, top = 4, bottom = 4}});
	self.CandyAnchorFrame:SetBackdropBorderColor(.5, .5, .5);
	self.CandyAnchorFrame:SetBackdropColor(0,0,0);
	self.CandyAnchorFrame.Text = self.CandyAnchorFrame:CreateFontString("$parentTime","ARTWORK","GameFontNormalLarge");
	self.CandyAnchorFrame.Text:SetPoint("CENTER", self.CandyAnchorFrame, "CENTER", 0, 0);
	self.CandyAnchorFrame.Text:SetVertexColor(1,1,1,1);
	self.CandyAnchorFrame.Text:SetText(L["Totem Timers"]);
	self.CandyAnchorFrame:EnableMouse(true);
	self.CandyAnchorFrame:RegisterForDrag("LeftButton");
	self.CandyAnchorFrame:SetMovable(true);
	self.CandyAnchorFrame:SetScript("OnDragStart", function() if(not self.db.profile.TimerBarLocked) then this:StartMoving(); end end);
	self.CandyAnchorFrame:SetScript("OnDragStop", function() this:StopMovingOrSizing(); self:SaveTimersPosition(); end);
	self.CandyAnchorFrame:SetScale(self.db.profile.TimerBarScale);
	self.CandyAnchorFrame:SetPoint( "CENTER", WorldFrame, "CENTER", 0,0 );
	self.TimerBarTextureHandle = SML:Fetch("statusbar",self.db.profile.TimerBarTexture);
	self:LoadTimersPosition();
end
function Yata:LoadTimersPosition()
	local x = 0;
	local y = 0;
	local scale = 1;
	if(self.db.profile.TimersPosition) then
		x = self.db.profile.TimersPosition.x;
		y = self.db.profile.TimersPosition.y;
		scale = self.CandyAnchorFrame:GetEffectiveScale();
	else
		self.CandyAnchorFrame:ClearAllPoints();
		self.CandyAnchorFrame:SetPoint( "CENTER", WorldFrame, "CENTER", 0,0 );
		scale = self.CandyAnchorFrame:GetEffectiveScale();
		x = self.CandyAnchorFrame:GetLeft()*scale;
		y = self.CandyAnchorFrame:GetBottom()*scale;
		self.db.profile.TimersPosition = {};
		self.db.profile.TimersPosition.x = x;
		self.db.profile.TimersPosition.y = y;
	end
	self.CandyAnchorFrame:SetPoint("BOTTOMLEFT", UIParent,"BOTTOMLEFT", x/scale, y/scale);
	self:SetCandyBarGroupPoint("YataCandy","CENTER",self.CandyAnchorFrame,"CENTER",0,25*self.db.profile.TimerBarScale);
end

function Yata:SaveTimersPosition()
	if not self.db.profile.TimersPosition then
		self.db.profile.TimersPosition = {};
	end
	local scale = self.CandyAnchorFrame:GetEffectiveScale();
	local x = self.CandyAnchorFrame:GetLeft()*scale;
	local y = self.CandyAnchorFrame:GetBottom()*scale;
	self.db.profile.TimersPosition.x = x;
	self.db.profile.TimersPosition.y = y;
end

-- If something triggers a potential Totemstomp we check for it and start the timer if necessary
function Yata:CheckHook(SpellName)
	local istotem = nil;
	if (string.find(string.lower(SpellName), string.lower(L["Totem"]))  and not self:SpellBlacklist(SpellName)) then
		istotem = true;
	elseif (SpellName == BS["Totemic Call"]) then
		istotem = nil;
	else return end;
	for k,b in pairs(self.TotemBar.Buttons) do
		if(istotem and SpellName == b.Totem.Name) then
			if(self.db.profile.TimersEnabled) then
				b.CurrentHealth = b.Totem.Health;
				self:StartTimer(b.ButtonID);
			end
			break;
		elseif(b.TimeStart and not istotem) then
			if(self.db.profile.TimersEnabled) then
				self:StopTimer(b.ButtonID);
			end
		end
	end
end

--------------
-- Cooldown --
--------------

function Yata:StartTimer(ID)
	if(self:IsCandyBarRegistered(self.TotemBar.Buttons[ID].Totem.Element.."DurationBar")) then	
		-- if another totem with the same element is thrown --	
		for k,b in pairs(self.TotemBar.Buttons) do 
			if(b.TimeStart and b.Totem.Element == self.TotemBar.Buttons[ID].Totem.Element) then
				self:StopTimer(b.ButtonID);
				break;
			end
		end
	end
	self.TotemBar.Buttons[ID].TimeStart = time();
	self:RegisterCandyBar(self.TotemBar.Buttons[ID].Totem.Element.."DurationBar",self.TotemBar.Buttons[ID].Totem.Duration,self.TotemBar.Buttons[ID].Totem.Name,self.TotemBar.Buttons[ID].Totem.Texture,"green","yellow","orange","red");
	self:RegisterCandyBarWithGroup(self.TotemBar.Buttons[ID].Totem.Element.."DurationBar", "YataCandy");
	self:SetCandyBarCompletion(self.TotemBar.Buttons[ID].Totem.Element.."DurationBar", function(ID) Yata:StopTimer(ID) end, ID);	
	self:SetCandyBarTexture(self.TotemBar.Buttons[ID].Totem.Element.."DurationBar", self.TimerBarTextureHandle);
	self:StartCandyBar(self.TotemBar.Buttons[ID].Totem.Element.."DurationBar", false);
	self:SetCandyBarScale(self.TotemBar.Buttons[ID].Totem.Element.."DurationBar",self.db.profile.TimerBarScale);
end
function Yata:StopTimer(ID)
	self:StopCandyBar(self.TotemBar.Buttons[ID].Totem.Element.."DurationBar");
	if(self.TotemBar.Buttons[ID].Totem.Cooldown > 0) then
		local count = time() - self.TotemBar.Buttons[ID].TimeStart;
		if(count < self.TotemBar.Buttons[ID].Totem.Cooldown) then
			self:Cooldown(ID,self.TotemBar.Buttons[ID].Totem.Cooldown-count);
		end
	end
	self.TotemBar.Buttons[ID].TimeStart = nil;
end
function Yata:Cooldown(ID, count)
	self:RegisterCandyBar(self.TotemBar.Buttons[ID].Totem.Name.."CooldownBar",count,self.TotemBar.Buttons[ID].Totem.Name.." Cooldown",self.TotemBar.Buttons[ID].Totem.Texture,"red","orange","yellow","green");
	self:RegisterCandyBarWithGroup(self.TotemBar.Buttons[ID].Totem.Name.."CooldownBar", "YataCandy");
	self:SetCandyBarTexture(self.TotemBar.Buttons[ID].Totem.Name.."CooldownBar", self.TimerBarTextureHandle);
	self:StartCandyBar(self.TotemBar.Buttons[ID].Totem.Name.."CooldownBar",true);
	self:SetCandyBarScale(self.TotemBar.Buttons[ID].Totem.Name.."CooldownBar",self.db.profile.TimerBarScale);
end